
//#include "head.h"
//#include <stdio.h>
#include <signal.h>

#include <iostream>

#include <workflow/WFFacilities.h>
#include <workflow/WFHttpServer.h>
#include <workflow/HttpUtil.h>
#include <workflow/HttpMessage.h>
using std::cout;
using std::endl;
using std::string;

//初始化计数器的值为1
static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf(">> sig num %d is comming\n", num);
    //调用一次done方法，计数器的值减1
    waitGroup.done();
}

void process(WFHttpTask * serverTask)
{
    printf("process is running.\n");
    //0. 对任务进行错误的检测
    int state = serverTask->get_state();
    int error = serverTask->get_error();
    printf("state: %d\n", state);
    switch(state) {
    case WFT_STATE_SYS_ERROR:
        printf("system error: %s\n", strerror(error)); break;
    case WFT_STATE_DNS_ERROR:
        printf("dns error: %s\n", gai_strerror(error)); break;
    case WFT_STATE_TOREPLY:
        break;
    }

    if(WFT_STATE_TOREPLY != state) {
        printf("error occurs!\n");
    }

    //1. 解析客户端请求
    auto req = serverTask->get_req();
    //1.1 起始行
    string method(req->get_method());
    printf("%s %s %s\n", req->get_method(),
           req->get_request_uri(),
           req->get_http_version());

    //1.2 首部字段
    protocol::HttpHeaderCursor cursor(req);
    string name, value;
    while(cursor.next(name, value)) {
        cout << name << ": " << value << endl;
    }
    cout << endl;
    //1.3 消息体
    if(method == "POST") {
        const void * body = nullptr;
        size_t sz = 0;
        req->get_parsed_body(&body, &sz);
        string strbody((const char *)body, sz);
        cout << strbody << endl;
    }

    //2. 处理数据
    //...

    //3. 生成响应
    //先获取到resp，但此时还没有任何数据
    auto resp = serverTask->get_resp();
    string strbody = "<html><body>hello, client</body></hmtl>";
    resp->add_header_pair("Content-Type", "text/html");
    resp->append_output_body(strbody);
}

void test0()
{
    signal(SIGINT, sighandler);
    //当调用wait方法会阻塞当前线程
    
    WFHttpServer httpServer(process);
    httpServer.start(8888);

    waitGroup.wait();

    cout << "test0 exit" << endl;
}


int main()
{
    test0();
    return 0;
}

